import 'package:flutter/material.dart';
import '../animation/moveDownHide.dart';
import '../mixin/buttonSwitch.dart';
import '../mixin/listAnim.dart';
import '../public/publicMethods.dart';
import 'dart:convert';

import 'package:flutter/services.dart';
//MethodChannel
const methodChannel = const MethodChannel('samples.flutter.dev/test');

// 代码块 statelessW
class Login extends StatelessWidget  {
  const Login({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return orderBody();
  }
}

class orderBody extends StatefulWidget {
  @override
  _DatePickerExampleState createState() => new _DatePickerExampleState();
}



/// RestorationProperty objects can be used because of RestorationMixin.
class _DatePickerExampleState extends State<orderBody> with SingleTickerProviderStateMixin,buttonSwitch,listAnim  {
  double getStatusBarHeight() {
    return MediaQuery.of(context).padding.top;
  }

  double sStatusBarHeighttop = 0;

  String account = '';
  String password = '';

  String loginState = '登陆';

  double rem = 0;
  double BGszie = 3000;
  double BGreadRadius = 0;

  late Animation<double> animation;
  late AnimationController controller;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    controller = AnimationController(duration: const Duration(milliseconds: 500), vsync: this);
    animation = CurvedAnimation(parent: controller, curve: Curves.easeInOut)..addListener(() {
      Tween<double> _blurRadiusTween = Tween<double>(begin: 3000,end:300);
      Tween<double> _blurRadiusTweens = Tween<double>(begin: 0,end:990);
      Tween<double> _blurRadiusTweenss = Tween<double>(begin: 0,end:getStatusBarHeight());

      setState(() {
        BGszie =_blurRadiusTween.evaluate(animation);
        sStatusBarHeighttop  =_blurRadiusTweenss.evaluate(animation);
        BGreadRadius =_blurRadiusTweens.evaluate(animation);
      });

    });

    initAnim();
  }

  endAnim(){

    for(var i=0;i<(listAnimData['main'] as List<double>).length;i++){
      Future.delayed(Duration(milliseconds: (150*i)), () {

        (listAnimData['main'] as List<double>)[i] = 2;
        setState(() {
        });
      });
    }
  }

  pushRoute(context,path){
    endAnim();
    Future.delayed(Duration(milliseconds: 400), () {

      ScaffoldMessenger.of(context).hideCurrentSnackBar();

      (controller as AnimationController).reset();
      (controller as AnimationController).forward();

      // setState(() {
      //   BGszie = 300;
      // });
      Future.delayed(Duration(milliseconds: 500), () {
        Navigator.of(context).pushNamedAndRemoveUntil( path, ModalRoute.withName(path));
      });
      //Navigator.of(context).pushNamedAndRemoveUntil( path, ModalRoute.withName(path));

    });
  }

  initAnim(){
    Future.delayed(Duration(milliseconds: (150)), () {
      for(var i=0;i<(listAnimData['main'] as List<double>).length;i++){
          Future.delayed(Duration(milliseconds: (150*i)), () {

            (listAnimData['main'] as List<double>)[i] = 1;
            setState(() {
              //pListAnim[i] = 1;
            });
          });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    rem =  MediaQuery.of(context).size.width/1080;

    return Scaffold(
        body: Container(
          width: 99999,
            height: 99999,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/bg3.jpg'),
                fit: BoxFit.cover,
              ),
            ),
            child:Stack(
              alignment: Alignment.center,
              children: [

                Align(
                    alignment: Alignment(0,0),
                    child:Container(
                      margin: EdgeInsets.fromLTRB(0, sStatusBarHeighttop, 0, 0),
                      width:BGszie*rem,
                      height:BGszie*rem,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage('assets/images/bg2.jpg'),
                            fit: BoxFit.cover,
                          ),
                          borderRadius: BorderRadius.circular(BGreadRadius)
                      ),
                    )
                ),
                Container(
                  width: 900*rem,
                  child:Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      MoveDownHide(
                        child: Text('用户登陆',style:TextStyle( fontSize: 60*rem)),
                        state: getListAnimData(key:'main',index:0),
                      ),

                      MoveDownHide(
                        state: getListAnimData(key:'main',index:1),
                        child:  Container(
                          margin: EdgeInsets.fromLTRB(0, 200*rem, 0, 0),
                          child:
                          TextField(
                            textAlign: TextAlign.center,
                            key:Key('username'),
                            onChanged: (text) {
                              setState(() {
                                account = text;
                              });
                            },
                            style: TextStyle(fontSize: 50*rem),
                            keyboardType:TextInputType.emailAddress,
                            decoration: InputDecoration(
                              hintText: '用户账号',
                              border: InputBorder.none, // 移除边框
                              filled: true, // 使用填充色
                              fillColor: Colors.white, // 填充色设置为白色
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(30*rem)), // 圆角
                                borderSide: BorderSide.none, // 边框无样式
                              ),
                              disabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(30*rem)), // 圆角
                                borderSide: BorderSide.none, // 边框无样式
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(30*rem)), // 圆角
                                borderSide: BorderSide.none, // 边框无样式
                              ),
                              errorBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(30*rem)), // 圆角
                                borderSide: BorderSide.none, // 边框无样式
                              ),
                              focusedErrorBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(30*rem)), // 圆角
                                borderSide: BorderSide.none, // 边框无样式
                              ),
                            ),
                          ),
                        ),

                      ),

                      MoveDownHide(
                        child:   Container(
                          margin: EdgeInsets.fromLTRB(0, 40*rem, 0, 0),
                          child:
                          TextField(
                            textAlign: TextAlign.center,
                            key:Key('username'),
                            onChanged: (text) {
                              setState(() {
                                password = text;
                              });
                            },
                            style: TextStyle(fontSize: 50*rem),
                            keyboardType:TextInputType.emailAddress,
                            obscureText:true,
                            decoration: InputDecoration(
                              hintText: '密码',
                              border: InputBorder.none, // 移除边框
                              filled: true, // 使用填充色
                              fillColor: Colors.white, // 填充色设置为白色
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(30*rem)), // 圆角
                                borderSide: BorderSide.none, // 边框无样式
                              ),
                              disabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(30*rem)), // 圆角
                                borderSide: BorderSide.none, // 边框无样式
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(30*rem)), // 圆角
                                borderSide: BorderSide.none, // 边框无样式
                              ),
                              errorBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(30*rem)), // 圆角
                                borderSide: BorderSide.none, // 边框无样式
                              ),
                              focusedErrorBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(30*rem)), // 圆角
                                borderSide: BorderSide.none, // 边框无样式
                              ),
                            ),
                          ),
                        ),

                        state: getListAnimData(key:'main',index:2),
                      ),

                      MoveDownHide(
                        child:     Container(
                            width: 900*rem,
                            height: 180*rem,
                            margin: EdgeInsets.fromLTRB(0,60*rem, 0, 0),
                            child: ElevatedButton.icon(
                                icon: Visibility(
                                  visible: loginState=='登陆中' || loginState=='',
                                  child: Container(
                                    width:60*rem,
                                    height: 60*rem,
                                    child: loginState==''? Icon(Icons.check) :CircularProgressIndicator(strokeWidth: 2,  color: Colors.white),
                                  ),
                                ),
                                style:ButtonStyle(
                                  backgroundColor:MaterialStateProperty.all( !((password!='' && account!='') && (getButtonState(key:'login') as bool))? Color.fromRGBO(100, 100, 100, 1):Color.fromRGBO(11, 135, 255, 1)),
                                  foregroundColor: MaterialStateProperty.all(Colors.white),
                                  shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(20*rem))),
                                ),
                                label:
                                Padding(
                                  padding:  EdgeInsets.fromLTRB(0,0,0,0),
                                  child:
                                  Text(loginState,
                                      style:TextStyle(
                                        fontSize:60*rem,
                                        fontWeight: FontWeight.bold,
                                      )
                                  ),
                                ),
                                onPressed: ()  async{

                                  if(((password!='' && account!='') && (getButtonState(key:'login') as bool))){
                                    setButtonState( key:'login', switchBool:false);

                                    setState(() {
                                      loginState = '登陆中';
                                    });

                                    Map response = await ajax.post(path:'/competition-app/public/api/users/login',body:{"password":password,"user":account});

                                    if(response['statusCode'] == 200){
                                      Map<String, dynamic> userMap = jsonDecode(response['body']);
                                      print(userMap);
                                      if(userMap['code'] == 1){
                                        final int result = await methodChannel.invokeMethod('saveSharedPreferences',{
                                          "key":"token",
                                          "value":userMap['data']['token']
                                        });

                                        setState(() {
                                          loginState = '登陆成功';
                                        });

                                        Future.delayed(Duration(milliseconds:2000), () {
                                          pushRoute(context, "/app");
                                        });



                                      }else{
                                        setButtonState( key:'login', switchBool:true);
                                        setState(() {
                                          loginState = '登陆';
                                        });
                                        ScaffoldMessenger.of(context).removeCurrentSnackBar();
                                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                                          content: Text(
                                              '账号或者密码错误'),
                                        ));
                                      }
                                    }else{
                                      setButtonState( key:'login', switchBool:false);
                                    }






                                  }
                                }
                            )
                        ),
                          state: getListAnimData(key:'main',index:3),
                      ),



                    ],
                  ) ,
                )

              ],
            )
        )
    );
  }
}

